package com.base.commons.elasticsearch.override;

import org.frameworkset.elasticsearch.boot.BBossESStarter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;


/**
 * @author carl
 */
public class EsMapperProxyFactory<T> implements FactoryBean<T> {

    private Class<T> esMapperInterface;
    @Autowired
    private BBossESStarter bBossESStarter;
    @Value("${elasticsearch.esMapperLocations:esmapper}")
    private String esMapperLocations;


    public EsMapperProxyFactory(Class<T> esMapperInterface) {
        this.esMapperInterface = esMapperInterface;
    }

    @Override
    public T getObject() throws Exception {
        //这里主要是创建接口对应的实例，便于注入到spring容器中
         String configFile =esMapperLocations +File.separator+ esMapperInterface.getSimpleName()+".xml";
        InvocationHandler handler = new EsMapperProxy(esMapperInterface, bBossESStarter.getConfigRestClient(configFile));
        return (T) Proxy.newProxyInstance(esMapperInterface.getClassLoader(),
                new Class[] {esMapperInterface},handler);
    }

    @Override
    public Class<T> getObjectType() {
        return esMapperInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }




}
